﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLogicLayer;
using CommonUtils;
using Resources;
using System.Drawing;
using System.IO;

namespace LiveCPEProject.profile
{
    public partial class ProfileEdition : System.Web.UI.Page
    {
        protected static Boolean isCreating = false;
        protected static Boolean isUpdating = false;
        protected static Boolean isCreated = false;
        protected static Boolean isUpdated = false;

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!Context.User.Identity.IsAuthenticated)
                {
                    Response.Redirect("~/login/Login.aspx");
                }

                if (!IsPostBack)
                {
                    if (Request.Params["new"] == null)
                    {
                        EntityDataModel.User user = UserBLL.GetUserByUserName(Context.User.Identity.Name);
                        if (user != null)
                        {
                            TextBoxFirstName.Text = user.FirstName;
                            TextBoxLastName.Text = user.LastName;
                            TextBoxEmail.Text = UserBLL.GetEmail(Context.User.Identity.Name);
                            if (user.DateOfBirth.HasValue)
                            {
                                TextBoxDateOfBirth.Text = user.DateOfBirth.Value.ToShortDateString();
                            }
                            RadioButtonGender_Female.Checked = true;
                        }
                    }
                    else
                    {
                        TextBoxEmail.Text = UserBLL.GetEmail(Context.User.Identity.Name);
                    }
                }

                if (Request.Params["new"] != null)
                {
                    Subtitle.Text = (String)GetGlobalResourceObject("LocalizedText", "Profile_SubtitleCreation");
                }
                else
                {
                    Subtitle.Text = (String)GetGlobalResourceObject("LocalizedText", "Profile_SubtitleModification");
                }
            }
            catch (Exception ee)
            {
                System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame();
                LogWriter.AddLog(ee, LogStatus.Error, GlobalParameters.ApplicationDisplayName, sf.GetMethod().Name);
                throw new Exception(sf.GetMethod().Name + " unexpected error", ee);
            }
        }

        protected void UpdateOrCreateUser(object sender, EventArgs e)
        {
            try
            {
                Boolean gender = RadioButtonGender_Male.Checked ? false : true;
                if(!UserBLL.IsUser(Context.User.Identity.Name))
                {
                    UserBLL.CreateUser(Context.User.Identity.Name, TextBoxFirstName.Text, TextBoxLastName.Text, gender, DateTime.Parse(TextBoxDateOfBirth.Text));
                    isCreated = true;
                    isCreating = false;
                }
                else
                {
                    UserBLL.UpdateUser(Context.User.Identity.Name, TextBoxFirstName.Text, TextBoxLastName.Text, gender, DateTime.Parse(TextBoxDateOfBirth.Text), TextBoxEmail.Text);
                    isUpdated = true;
                    isUpdating = false;
                }
                UpdatePicture();
            }
            catch (Exception ee)
            {
                System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame();
                LogWriter.AddLog(ee, LogStatus.Error, GlobalParameters.ApplicationDisplayName, sf.GetMethod().Name);
                throw new Exception(sf.GetMethod().Name + " unexpected error", ee);
            }
        }

        protected void UpdateOrCreate(object sender, EventArgs e)
        {
            try
            {
                if (Request.Params["new"] != null)
                {
                    isCreating = true;
                }
                else
                {
                    isUpdating = true;
                }
            }
            catch (Exception ee)
            {
                System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame();
                LogWriter.AddLog(ee, LogStatus.Error, GlobalParameters.ApplicationDisplayName, sf.GetMethod().Name);
                throw new Exception(sf.GetMethod().Name + " unexpected error", ee);
            }
        }

        protected void UpdatePicture()
        {
            try
            {
                // If file field is not empty
                if (FileUploader.PostedFile != null)
                {
                    // Check file size (must not be 0)
                    HttpPostedFile myFile = FileUploader.PostedFile;
                    int nFileLen = myFile.ContentLength;
                    if (nFileLen == 0)
                    {
                        UploadLabel.Text = "No file was uploaded.";
                        return;
                    }

                    // Check file extension (must be JPG)
                    if (System.IO.Path.GetExtension(myFile.FileName).ToLower() != ".jpg")
                    {
                        UploadLabel.Text = "The file must have an extension of JPG";
                        return;
                    }

                    // Read file into a data stream
                    byte[] myData = new Byte[nFileLen];
                    myFile.InputStream.Read(myData, 0, nFileLen);
                    
                    // Save the stream to database
                    UserBLL.UpdatePictureForUser(Context.User.Identity.Name, myData);
                }
            }
            catch (Exception ee)
            {
                System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame();
                LogWriter.AddLog(ee, LogStatus.Error, GlobalParameters.ApplicationDisplayName, sf.GetMethod().Name);
                throw new Exception(sf.GetMethod().Name + " unexpected error", ee);
            }
        }

        protected Boolean ThumbnailCallback()
        {
            return false;
        }

        protected void ClearFields(object sender, EventArgs e)
        {
            try
            {
                TextBoxFirstName.Text = "";
                TextBoxLastName.Text = "";
                TextBoxEmail.Text = "";
                TextBoxDateOfBirth.Text = "";
            }
            catch (Exception ee)
            {
                System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame();
                LogWriter.AddLog(ee, LogStatus.Error, GlobalParameters.ApplicationDisplayName, sf.GetMethod().Name);
                throw new Exception(sf.GetMethod().Name + " unexpected error", ee);
            }
        }

        [System.Web.Services.WebMethod]
        [System.Web.Script.Services.ScriptMethod]
        public static string[] GetUserNameList(string prefixText, int count, string contextKey)
        {
            try
            {
                String[] listUserNames = UserBLL.GetAllUserNames();
                return (from l in listUserNames where l.Contains(prefixText) select l).Take(count).ToArray();
            }
            catch (Exception ee)
            {
                System.Diagnostics.StackFrame sf = new System.Diagnostics.StackFrame();
                LogWriter.AddLog(ee, LogStatus.Error, GlobalParameters.ApplicationDisplayName, sf.GetMethod().Name);
                throw new Exception(sf.GetMethod().Name + " unexpected error", ee);
            }
        }
    }
}